/*
 * author: fieldyang
 * mail:fieldyang@163.com
 */
package action.common;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import common.impl.JValidatorImpl;
import common.impl.exception.ServiceException;
import common.interf.IErrorHandle;
import common.interf.IServletHandle;

@SuppressWarnings("unchecked")
public class MyBaseAction<T> extends ActionSupport {
	private static final long serialVersionUID = 4553870227420697820L;
	protected Map<String,String> validRules = new HashMap<String,String>();
	protected IServletHandle servletHandle;
	protected IErrorHandle errorHandle;;
	protected final Log log = LogFactory.getLog(getClass());
	protected T model;
	
	
	public void setServletHandle(IServletHandle servletHandle) {
		this.servletHandle = servletHandle;
	}

	public void setErrorHandle(IErrorHandle errorHandle) {
		this.errorHandle = errorHandle;
	}

	public MyBaseAction(Class clazz){
		if(clazz == null)
			return;
		try{
			this.model=(T)clazz.newInstance();	
		}catch(Exception e){
			model = (T)this;
		}
	}
	/**
	 * 检查session
	 * @return
	 */
	public Long getSessionUID() throws ServiceException {
		Object o = ServletActionContext.getRequest().getSession().getAttribute("userId");
		if(o == null)
			throw new ServiceException("ERR-0018");
		return (Long)o;
	}
	/**
	 * 验证
	 * @param fieldStr：要验证的字段，以","分割，如果有拦截，以"|"分割 
	 * @return 通过 true 没通过 false 
	 */
	public boolean validMe(String fieldStr){
		String r = validMeWithResult(fieldStr);
		if(null != r){
			servletHandle.writeToClient1(ServletActionContext.getResponse(), r);
			return false;
		}
		return true;
	}
	
	/**
	 * 验证
	 * @param fieldStr：要验证的字段，以","分割，如果有拦截，以"|"分割 
	 * @return 通过 true 没通过 false 
	 */
	public boolean validMe(String fieldStr,String type){
		String r = validMeWithResult(fieldStr);
		if(null != r){
			servletHandle.writeToClient1(ServletActionContext.getResponse(),r,type);
			return false;
		}
		return true;
	}
	/**
	 * 验证（返回结果）  
	 * @param fieldStr：要验证的字段，以","分割，如果有拦截，以"|"分割 
	 * @return 通过 true 没通过 false 
	 */
	public String validMeWithResult(String fieldStr){
		String[] fields = fieldStr.split(",");
		int len = fields.length;
		StringBuffer msgs = new StringBuffer("");
		JValidatorImpl jvalidator = new JValidatorImpl();
		for(int i=0;i<len;i++){
			String []farr = fields[i].split("\\|");
			String bfield = farr[0].substring(0, 1).toUpperCase() + farr[0].substring(1);
			String md = "val" + bfield;
			Method method = null;
			String eStr = null;
			String getValue = "get" + bfield; 
			try{
				method = this.getClass().getMethod(md);
			}catch(Exception e){
				//continue;
			}
			//存在自定义验证函数
			if(null != method){
				try{
					eStr = (String)method.invoke(this);
				}catch(Exception e){
					continue;
				}
			}else{
				//不存在自定义验证函数
				String fieldValue = null;
				try{
					fieldValue = model.getClass().getMethod(getValue).invoke(model, null).toString(); 
				}catch(Exception e){
					log.info(e);
				}
				//不存在参数值
				if(null == fieldValue){
					try{
						fieldValue = this.getClass().getMethod(getValue).invoke(this, null).toString(); 
					}catch(Exception e){
						//log.info(e);
					}
				}
				String rule = (String)validRules.get(fields[i]);
				if(null == rule)
					continue;
				String[] rules = rule.split("\\|");
				int len1 = rules.length;
				for(int j=0;j<len1;j++){
					String[] params = null;
					int x = rules[j].indexOf("(");
					int x1 = rules[j].indexOf(")");
					String fdname = rules[j];
					if(x != -1 && x1 != 1 && x1 > x){
						params = rules[j].substring(x+1, x1).split(",");
						fdname = rules[j].substring(0,x); 
					}
					Method m = null;
					try{
						if("betweenLength".equals(fdname)){
							m = JValidatorImpl.class.getMethod("validateBetweenLength", String.class,Integer.class,Integer.class);
							if(!(Boolean)m.invoke(jvalidator, new Object[]{fieldValue,Integer.parseInt(params[0]),Integer.parseInt(params[1])}))
								eStr = getText("error.msg." + fdname,new String[]{params[0],params[1]});
						}
						else if("minLength".equals(fdname)){
							m = JValidatorImpl.class.getMethod("validateMinLength", String.class,Integer.class);
							if(!(Boolean)m.invoke(jvalidator, new Object[]{fieldValue,Integer.parseInt(params[0])}))
								eStr = getText("error.msg." + fdname,new String[]{params[0]});
							
						}
						else if("maxLength".equals(fdname)){
							m = JValidatorImpl.class.getMethod("validateMaxLength", String.class,Integer.class);
							if(!(Boolean)m.invoke(jvalidator, new Object[]{fieldValue,Integer.parseInt(params[0])}))
								eStr = getText("error.msg." + fdname,new String[]{params[0]});
						}
						else if("min".equals(fdname)){
							m = JValidatorImpl.class.getMethod("validateMin", Double.class,Double.class);
							if(!(Boolean)m.invoke(jvalidator, new Object[]{fieldValue,Double.parseDouble(params[0])}))
								eStr = getText("error.msg." + fdname,new String[]{params[0]});
						}
						else if("max".equals(fdname)){
							m = JValidatorImpl.class.getMethod("validateMax", Double.class,Double.class);
							if(!(Boolean)m.invoke(jvalidator, new Object[]{fieldValue,Double.parseDouble(params[0])}))
								eStr = getText("error.msg." + fdname,new String[]{params[0]});
						}
						else if("between".equals(fdname)){
							m = JValidatorImpl.class.getMethod("validateBetween", Double.class,Double.class,Double.class);
							if(!(Boolean)m.invoke(jvalidator, new Object[]{fieldValue,Double.parseDouble(params[0]),Double.parseDouble(params[1])}))
								eStr = getText("error.msg." + fdname,new String[]{params[0]});
						}
						else if("fileType".equals(fdname)){
							String param = rules[j].substring(x+1, x1);
							m = JValidatorImpl.class.getMethod("validateFileType", String.class,String.class);
							if(!(Boolean)m.invoke(jvalidator, new Object[]{fieldValue,param}))
								eStr = getText("error.msg." + fdname,new String[]{param});
						}
						else {
							String tmp = "validate" + fdname.substring(0,1).toUpperCase() + fdname.substring(1);	
							m = JValidatorImpl.class.getMethod(tmp, String.class);
							if(!(Boolean)m.invoke(jvalidator, new Object[]{fieldValue}))
								eStr = getText("error.msg." + fdname);
						}
					}catch(Exception e){
						log.info(e);
						continue;
					}
					if(null != eStr)
						break;
				}
			}
			if(null != eStr && !"".equals(eStr)){
				msgs.append("'" + farr[0] + "':'" + eStr + "',");
				if(farr.length>1) 
					break;
			}
		}
		len = msgs.length();
		if(len > 0){
			msgs.delete(len-1,len);
			JSONObject jobj = new JSONObject();
			jobj.put("msgs", "{" + msgs.toString() + "}");
			return jobj.toString();
		}
		return null;
	}
}
